<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #box {
      display: flex;
    }

    #box span {
      width: 120px;
      height: 45px;
      font-size: 25px;
      line-height: 45px;
      border: 1px solid black;
      text-align: center;
    }
  </style>
</head>

<body>
  <div id="box">
    <input type="text" id="txt"> <span id="veri">8374</span>
  </div>
  <button id="btn">验证</button>
  <script>
    var veriEle = document.getElementById("veri"); //验证码显示的元素
    var txt = document.getElementById("txt");//获取输入框
    var btn = document.getElementById("btn");//获取按钮

    var code = ""; //存储生成的验证码
    function makeCode() { //制作验证码函数 
      var arr = ["1", "2", "3", "4", "a", "b", "d", "A", "B", "C", "D", "E"];
      code = "";//清空上次的验证码
      for (var i = 0; i < 4; i++) {
        var num = Math.floor(Math.random() * arr.length);//随机下标
        code += arr[num] //把随机的字母拼接到code
      }
      veriEle.innerHTML = code;//显示验证码
      return code //返回验证码
    }
    makeCode(); //初始化显示验证码


    // 校验验证码 对比输入框 和生成的验证码是否相等
    btn.onclick = function () { //点击事件
      //  把生成的验证码转成小写   输入的验证转成小写 进行比较
      if (code.toLowerCase() == txt.value.toLowerCase()) {
        alert("验证码正确")
      } else {
        alert("验证码错误")
        txt.value = "";//清空输入框
        makeCode(); //从新生产验证码
      }
    }

    // 点击验证码  从新生成验证码
    veriEle.onclick = function () {
      makeCode(); //从新生产验证码
    }

  </script>
</body>

</html>